package com.liry.dowloadtgz;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Sublock {
    public static void main(String[] args) throws IOException {
        String rootPath = "D:\\npm-repository\\lowcode-demo";
        String lockMark = "package-lock";
        File lockFileDir = new File(rootPath);
        String[] files = lockFileDir.list();
        List<String> lockFiles = new ArrayList<>();
        for (String file : files) {
            if (file.contains(lockMark)) {
                lockFiles.add(file);
            }
        }
        Map<String, String> depMap = new HashMap<>();
        for (String lockFile : lockFiles) {
            readLock(depMap, rootPath + "/" + lockFile);
        }

        String rootLockpath = "D:\\npm-repository\\lowcode-demo\\package-ll.json";
        Map<String, String> rootLockMap = new HashMap<>();
        readLock(rootLockMap, rootLockpath);
        System.out.println("跟lock有：" + rootLockMap.size());
        System.out.println("子lock有：" + depMap.size());

        Set<String> rootLockSet = rootLockMap.keySet();
        Set<String> childLockSet = depMap.keySet();
        List<String> sub1 = CollectionUtil.subtractToList(childLockSet, rootLockSet);
        List<String> sub2 = CollectionUtil.subtractToList(rootLockSet, childLockSet);
        sub1.addAll(sub2);
        System.out.println("差值：" + sub1.size());

        for (String lockUrl : sub1) {
            String s = rootLockMap.get(lockUrl);
            if (s == null) {
                s = depMap.get(lockUrl);
            }
            DownloadTgz.downloadFile(rootPath + "\\child", s, lockUrl);
        }


    }

    public static void readLock(Map<String, String> depMap, String lockFile) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(lockFile));
        String tempStr = null;
        StringBuffer jsonStr = new StringBuffer();
        while ((tempStr = br.readLine()) != null) {
            jsonStr.append(tempStr);
        }
        JSONObject json = JSON.parseObject(jsonStr.toString());
        JSONObject dependencies = json.getJSONObject("dependencies");
        for (Map.Entry<String, Object> entry : dependencies.entrySet()) {
            String depName = entry.getKey();
            JSONObject value = (JSONObject) entry.getValue();
            String resolved = value.getString("resolved");
            depMap.put(resolved, depName);
        }
    }
}
